package com.jl.exception;

import com.jl.config.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;


@RestControllerAdvice
public class GlobalExceptionHandler {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public BaseResponse exceptionHandler(HttpServletRequest request, Exception e){
		this.logger.error("GlobalExceptionHandler:", e);
//		绑定异常是需要明确提示给用户的
		if(e instanceof RRException){
			RRException exception=(RRException) e;
			return BaseResponse.error(exception.getCode(), exception.getMsg());//将具体
		}
		if (e instanceof MethodArgumentNotValidException){
			BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
			return BaseResponse.error("444",bindingResult.getFieldError().getField()+
					bindingResult.getFieldError().getDefaultMessage());
		}
		if (e instanceof DataIntegrityViolationException){
			return BaseResponse.error("443",e.getMessage());
		}
//		if (e instanceof MySQLIntegrityConstraintViolationException){
//			return  BaseRespons.error("442",e.getMessage());
//		}
		String message = e.getMessage();
		return BaseResponse.error("500", "系统异常-" + message);
	}
}
